package com.extension.company.common.http;

import com.extension.company.admin.BuildConfig;
import com.extension.company.model.api.RetrofitUrlApi;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * create zwk
 * data 2019/2/28
 * 功能：retrofit提供者
 */
public class RetrofitHelper {

//    private RetrofitHelper(){}
//
//    private static class SingleHolder {
//        private static final RetrofitHelper INSTANCE = new RetrofitHelper();
//    }
//
//    public static RetrofitHelper getInstance() {
//        return SingleHolder.INSTANCE;
//    }
//
//    public Retrofit getRetrofit () {
//        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl(Urls.url)
//                .addConverterFactory(GsonConverterFactory.create())
//                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(new IoScheduler()))
//                .build();
//        return retrofit;
//    }

	private volatile static Retrofit retrofit;

	public static Retrofit getRetrofit() {
		if (retrofit == null) {
			synchronized (RetrofitHelper.class) {
				if (retrofit == null) {
					OkHttpClient.Builder builder = new OkHttpClient.Builder()
							.connectTimeout(10, TimeUnit.SECONDS)
							.readTimeout(15, TimeUnit.SECONDS)
							.writeTimeout(15, TimeUnit.SECONDS)
							.retryOnConnectionFailure(true);

					if (BuildConfig.DEBUG) {
						initInterceptor(builder);
					}

					retrofit = new Retrofit.Builder()
							.baseUrl(RetrofitUrlApi.BaseHostUrl)
							.client(builder.build())
							.addConverterFactory(GsonConverterFactory.create())
							.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
							.build();

				}
			}
		}
		return retrofit;
	}

	/**
	 * 设置okhttp的拦截器
	 *
	 * @param builder
	 * @return
	 */
	private static OkHttpClient.Builder initInterceptor(OkHttpClient.Builder builder) {
		HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
		loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // 请求、响应行+头+体
//		loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); // 请求、响应行
//		loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);// 请求/响应+头
		builder.addInterceptor(loggingInterceptor);
		return null;
	}

}
